/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.menosehmais.framework.converter;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.ioc.ApplicationScoped;
import java.util.ResourceBundle;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;

/**
 * ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSS).
 * @see LocalDateConverter
 * @see LocalTimeConverter
 * @author Quintino
 */
//@Convert(LocalDateTime.class)
//@ApplicationScoped
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    @Override
    public LocalDateTime convert(String value, Class<? extends LocalDateTime> type, ResourceBundle bundle) {
        return fromString(value);
    }

    public static LocalDateTime fromString(String value) {
        LocalDate date = null;
        LocalTime time = null;
        LocalDateTime dateTime = null;

        try {
            if (value == null || value.trim().isEmpty()) {
                return null;
            } else {
                value = value.trim().toUpperCase();
                if(value.matches("^\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}(:\\d{1,2}(\\.\\d{1,3})?)?$")) {

                    String fields[] = value.split("T");
                    date = LocalDateConverter.fromString(fields[0]);
                    time = LocalTimeConverter.fromString(fields[1]);

                    if(date != null && time != null) {
                        dateTime = new LocalDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                                time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(), time.getMillisOfSecond());
                        
                        return dateTime;
                    }
                }
            }
        } catch (Exception e) {
            throw new ConversionError( "LocalDateTime: " + value + ", é inválido. " + e.getMessage() );
        }
        throw new ConversionError( "LocalDateTime: " + value + ", é inválido. " );
    }

    public static String asString(LocalDateTime dateTime){
        if(dateTime == null) {
            return null;
        }
        return dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS");
    }
}
